package com.ruoyi.sl.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import cn.hutool.core.util.ArrayUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.sl.domain.*;
import com.ruoyi.sl.mapper.*;
import com.ruoyi.sl.pojo.SlReportDetailQuery;
import com.ruoyi.sl.pojo.SlSinglePayQuery;
import com.ruoyi.sl.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 日工资Service业务层处理
 * 
 * @author admin
 * @date 2024-06-20
 */
@Service
public class SlWagesDayServiceImpl implements ISlWagesDayService 
{
    @Autowired
    private SlWagesDayMapper slWagesDayMapper;
    @Autowired
    private SlDeductionMapper slDeductionMapper;
    @Autowired
    private SlRworkMapper slRworkMapper;

    @Autowired
    private ISlWsbaseService slWsbaseService;
    @Autowired
    private ISlTeamMemberService slTeamMemberService;
    @Autowired
    private ISlRfworkService slRfworkService;
    @Autowired
    private ISlAttendanceService slAttendanceService;
    @Autowired
    private ISlRworkService slRworkService;
    @Autowired
    private ISlProcessService slProcessService;
    @Autowired
    private ISlRworkRmemberService slRworkRmemberService;
    @Autowired
    private ISlSaService slSaService;
    @Autowired
    private ISlSpecialService slSpecialService;
    @Autowired
    private ISlWagesDayService slWagesDayService;
    @Autowired
    private ISlApprenticeService slApprenticeService;
    @Autowired
    private ISlOddjobAttendanceService slOddjobAttendanceService;
    @Autowired
    private ISlOddjobService slOddjobService;
    @Autowired
    private ISlOddjobOmemberService slOddjobOmemberService;


    //获取日期范围内出勤天数>=0.5的次数
    @Override
    public BigDecimal selectMealAllowanceCountByUserAndDate(Date startDate,Date endDate,String userName){
        return slWagesDayMapper.selectMealAllowanceCountByUserAndDate(startDate,endDate,userName);
    }

    /**
     * 查询日工资
     * 
     * @param wagesDayId 日工资主键
     * @return 日工资
     */
    @Override
    public SlWagesDay selectSlWagesDayByWagesDayId(Long wagesDayId)
    {
        return slWagesDayMapper.selectSlWagesDayByWagesDayId(wagesDayId);
    }

    //查询条件查询工资
    @Override
    public List<SlWagesDay> selectSlWagesDayByQuery(SlSinglePayQuery slSinglePayQuery){
        return slWagesDayMapper.selectSlWagesDayByQuery(slSinglePayQuery);
    }


    /**
     * 查询日工资
     *
     * @param rfworkId 报工单ID
     * @param userName 用户名
     * @return 日工资
     */
    public SlWagesDay selectSlWagesDayByRfworkIdAndUser(Long rfworkId, String userName){
        return slWagesDayMapper.selectSlWagesDayByRfworkIdAndUser(rfworkId,userName);
    }



    /**
     * 查询条件和日期查询工资总额和结算出勤总天数
     *
     * @param slWagesDay 参数
     * @return 日工资
     */
    public SlWagesSettlementDays selectTotalWagesDaysByUserAndType(SlWagesDay slWagesDay){
        return slWagesDayMapper.selectTotalWagesDaysByUserAndType(slWagesDay);
    }


    /**
     * 查询指定日期之间的所有人员薪资和出勤天数
     *
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 日工资
     */
    public List<SlWagesDay> selectTotalWagesDayListByDate(Date startDate, Date endDate){
        return slWagesDayMapper.selectTotalWagesDayListByDate(startDate,endDate);
    }

    /**
     * 查询指定日期之间的所有人员工资信息
     */
    @Override
    public List<SlReportDetail> selectReportDetail(SlReportDetailQuery slReportDetailQuery){
        List<SlReportDetail> list = slWagesDayMapper.selectReportDetail(slReportDetailQuery);
        List<SlReportDetail> newlist = increaseAttendance(list);
        return newlist;
    }

    /**
     * 查询指定日期之间的所有零工人员工资信息
     */
    @Override
    public List<SlReportDetail> selectOddjobReportDetail(SlReportDetailQuery slReportDetailQuery){
        List<SlReportDetail> list = slWagesDayMapper.selectOddjobReportDetail(slReportDetailQuery);
        if(StringUtils.isNotEmpty(list)){
            for (SlReportDetail reportDetail:list) {
                SlWagesDay slWagesDay = slWagesDayMapper.selectAttendanceReportDetail(reportDetail.getRfworkId(),reportDetail.getMemberUser());
                if (StringUtils.isNotNull(slWagesDay)){
                    reportDetail.setProWages(slWagesDay.getProWages());
                    //reportDetail.setRfworkIdAndUser(reportDetail.getRfworkId().toString()+reportDetail.getRworkDate().toString());
                }
                reportDetail.setMemberDm(slDeductionMapper.selectDmAmountByRworkAndUser(reportDetail.getRfworkId(),reportDetail.getRworkId(),reportDetail.getMemberUser()));
            }
        }
        return list;
    }
    /**
     * 查询特殊系数日工资列表
     *
     * @return 日工资集合
     */
    @Override
    public List<SlReportDetail> selectSlWagesDayListByCoefficient(SlReportDetailQuery slReportDetailQuery){
        List<SlReportDetail> list = slWagesDayMapper.selectSlWagesDayListByCoefficient(slReportDetailQuery);
        List<SlReportDetail> newlist = increaseAttendance(list);
        return newlist;
    }

    //添加总出勤天数，工资之类的
    public List<SlReportDetail> increaseAttendance(List<SlReportDetail> list){
        if(StringUtils.isNotEmpty(list)){
            for (SlReportDetail reportDetail:list) {
                SlWagesDay slWagesDay = slWagesDayMapper.selectAttendanceReportDetail(reportDetail.getRfworkId(),reportDetail.getMemberUser());
                if (StringUtils.isNotNull(slWagesDay)){
                    reportDetail.setRworkAttendanceDay(slWagesDay.getProDay());
                    reportDetail.setRworkSettlementDay(slWagesDay.getProSettlement());
                    reportDetail.setProWages(slWagesDay.getProWages());
                    //reportDetail.setRfworkIdAndUser(reportDetail.getRfworkId().toString()+reportDetail.getRworkDate().toString());
                }
                reportDetail.setMemberDm(slDeductionMapper.selectDmAmountByRworkAndUser(reportDetail.getRfworkId(),reportDetail.getRworkId(),reportDetail.getMemberUser()));
                reportDetail.setRworkEstimatePay(slRworkMapper.selectAllPayByRfworkId(reportDetail.getRfworkId()));
            }
        }
        return list;
    }

    /**
     * 查询日工资列表
     * 
     * @param slWagesDay 日工资
     * @return 日工资
     */
    @Override
    public List<SlWagesDay> selectSlWagesDayList(SlWagesDay slWagesDay)
    {
        return slWagesDayMapper.selectSlWagesDayList(slWagesDay);
    }


    /**
     * 查询计件日工资列表
     *
     * @param slWagesDay 日工资
     * @return 日工资集合
     */
    @Override
    public List<SlWagesDay> selectSlWagesDayListByPiece(SlWagesDay slWagesDay){
        return slWagesDayMapper.selectSlWagesDayListByPiece(slWagesDay);
    }



    /**
     * 新增日工资
     * 
     * @param slWagesDay 日工资
     * @return 结果
     */
    @Override
    public int insertSlWagesDay(SlWagesDay slWagesDay)
    {
        slWagesDay.setCreateTime(DateUtils.getNowDate());
        return slWagesDayMapper.insertSlWagesDay(slWagesDay);
    }

    /**
     * 修改日工资
     * 
     * @param slWagesDay 日工资
     * @return 结果
     */
    @Override
    public int updateSlWagesDay(SlWagesDay slWagesDay)
    {
        slWagesDay.setUpdateTime(DateUtils.getNowDate());
        return slWagesDayMapper.updateSlWagesDay(slWagesDay);
    }

    /**
     * 批量删除日工资
     * 
     * @param wagesDayIds 需要删除的日工资主键
     * @return 结果
     */
    @Override
    public int deleteSlWagesDayByWagesDayIds(Long[] wagesDayIds)
    {
        return slWagesDayMapper.deleteSlWagesDayByWagesDayIds(wagesDayIds);
    }

    /**
     * 删除日工资信息
     * 
     * @param wagesDayId 日工资主键
     * @return 结果
     */
    @Override
    public int deleteSlWagesDayByWagesDayId(Long wagesDayId)
    {
        return slWagesDayMapper.deleteSlWagesDayByWagesDayId(wagesDayId);
    }

    //删除指定日期的工资记录
    @Override
    public int deleteSlWagesDayByDate(String workType, Date proDate){
        return slWagesDayMapper.deleteSlWagesDayByDate(workType,proDate);
    }

    @Transactional
    @Override
    public void countJiJianWsDay(SlRfwork paramRfwork)
    {

        System.out.println("start------------车间日工资计算开始--------------");

        //指定日期所有复核通过的计件报工单
        Date rworkDate = paramRfwork.getRfworkDate();

        //先删除当日所有计件工资记录
        slWagesDayService.deleteSlWagesDayByDate("0",rworkDate);

        //职级7初级8中级9高级学徒
        Long[] apprenticeIds = {new Long(7),new Long(8),new Long(9)};
        //1个出勤天=多少小时
        BigDecimal workHours = BigDecimal.valueOf(10);
        //车间薪资基础配置
        SlWsbase slWsbase = slWsbaseService.selectSlWsbaseByWsbaseId(1L);
        //特殊系数人员最后计算
        List<SlAttendance> lastAttendance = new ArrayList<>();
        //原皮库所有成员
        List<String> ypkUsers = new ArrayList<>();
        List<SlTeamMember> teamMemberList = slTeamMemberService.selectSlTeamMemberListByTeamCode("ypk");
        if(StringUtils.isNotEmpty(teamMemberList)){
            for (SlTeamMember teamMember:teamMemberList) {
                ypkUsers.add(teamMember.getUserName());
            }
        }

        List<SlRfwork> list = slRfworkService.selectAllApprovedSlRfworkListByDate("0",rworkDate);

        for (SlRfwork rfwork : list) {

            //根据出勤记录创建当日对应报工单工资记录
            List<SlAttendance> slAttendanceList = slAttendanceService.selectAllSlAttendanceByRfworkId(rfwork.getRfworkId());
            BigDecimal attendanceDay = BigDecimal.ZERO; //总出勤结算天数
            if (StringUtils.isNotEmpty(slAttendanceList)) {
                //计算每个人的结算比例
                for (SlAttendance slAttendance : slAttendanceList) {
                    BigDecimal tmpSettlementDay = slAttendance.getAttendanceDay();  //出勤结算天数
                    BigDecimal tmpCoefficient = BigDecimal.valueOf(1);  //工资系数
                    BigDecimal tmpScale = BigDecimal.valueOf(1);    //出勤结算比例

                    if (ArrayUtil.contains(apprenticeIds, slAttendance.getLevelId())) {
                        //学徒的按比例转换结算天数
                        SlApprentice slApprentice = new SlApprentice();
                        slApprentice.setModuleId(rfwork.getModuleId());
                        slApprentice.setLevelId(slAttendance.getLevelId());
                        slApprentice = slApprenticeService.selectSlApprenticeByModuleAndLevel(slApprentice);
                        if (StringUtils.isNotNull(slApprentice)){
                            tmpScale = slApprentice.getApprenticeDay();
                            tmpSettlementDay = tmpSettlementDay.multiply(tmpScale).setScale(2, RoundingMode.DOWN);
                        }
                    }else {
                        //特殊系数结算比例
                        Long ssmId = slAttendance.getSsmId();
                        SlSpecial slSpecial = slSpecialService.selectSlSpecialByUserName(slAttendance.getUserName());
                        if (StringUtils.isNotNull(slSpecial)){
                            if(ssmId==2 || ssmId==4){
                                //机台长系数工资，看他和报工人是不是一人，是一人的话按系数算
                                if(ssmId==2 && !slAttendance.getUserName().equals(rfwork.getRfworkUser())){

                                }else{
                                    if("1".equals(slSpecial.getIsProduce())){
                                        tmpSettlementDay = BigDecimal.ZERO;
                                        tmpScale = BigDecimal.ZERO;
                                    }else{
                                        tmpSettlementDay = tmpSettlementDay.multiply(slSpecial.getSsScale()).setScale(2,RoundingMode.DOWN);
                                        tmpScale = slSpecial.getSsScale();
                                    }
                                    tmpCoefficient = slSpecial.getSsRatio();
                                }

                            }
                        }
                    }

                    slAttendance.setScale(tmpScale);
                    slAttendanceService.updateSlAttendance(slAttendance);

                    attendanceDay = attendanceDay.add(tmpSettlementDay);

                    //特殊系数存起来最后算
                    if(slAttendance.getSsmId()==4){
                        lastAttendance.add(slAttendance);
                    }else{
                        //当日工资记录
                        SlWagesDay slWagesDay = new SlWagesDay();
                        slWagesDay.setLevelId(slAttendance.getLevelId());
                        slWagesDay.setSsmId(slAttendance.getSsmId());
                        slWagesDay.setModuleId(rfwork.getModuleId());
                        slWagesDay.setRfworkId(slAttendance.getRfworkId());
                        slWagesDay.setUserName(slAttendance.getUserName());
                        slWagesDay.setNickName(slAttendance.getNickName());
                        slWagesDay.setProDay(slAttendance.getAttendanceDay());
                        slWagesDay.setProSettlement(tmpSettlementDay);
                        slWagesDay.setWagesSacoefficient(tmpCoefficient);
                        slWagesDay.setProWages(BigDecimal.ZERO);
                        slWagesDay.setProDate(rfwork.getRfworkDate());
                        slWagesDay.setWorkType("0");
                        slWagesDayService.insertSlWagesDay(slWagesDay);
                    }
                }


                //鞋面报工单工资平分
                if (rfwork.getModuleId().longValue()==1L){
                    //报工单总工资
                    BigDecimal rfworkPay = slRworkService.selectAllPayByRfworkId(rfwork.getRfworkId());
                    //平分工资
                    //基础工资 = 报工单总工资/总出勤结算天数
                    BigDecimal dayBaseWages = rfworkPay.divide(attendanceDay,2,RoundingMode.DOWN).setScale(2,RoundingMode.DOWN);
                    for (SlAttendance slAttendance : slAttendanceList) {
                        //非特殊系数，非小时工，非学徒 更新工资
                        if(slAttendance.getSsmId().longValue() != 4L && slAttendance.getSsmId().longValue() != 5L && !ArrayUtil.contains(apprenticeIds, slAttendance.getLevelId())){

                            SlWagesDay slWagesDay = slWagesDayService.selectSlWagesDayByRfworkIdAndUser(slAttendance.getRfworkId(),slAttendance.getUserName());
                            //工资 = 基础工资X出勤天数X工资系数
                            if(StringUtils.isNotNull(slWagesDay)){
                                slWagesDay.setProWages(dayBaseWages.multiply(slWagesDay.getProDay()).multiply(slWagesDay.getWagesSacoefficient()).setScale(2,RoundingMode.DOWN));
                                slWagesDayService.updateSlWagesDay(slWagesDay);
                            }

                        }
                    }
                }
            }

            //沙发及水场工资处理，是报工项平分
            List<SlRwork> slRworkList = slRworkService.selectSlRworkListByRfworkId(rfwork.getRfworkId());
            if (StringUtils.isNotEmpty(slRworkList)){
                //获取报工单所有报工项的工序，判断有没有定量
                Map<Long, BigDecimal> tmpMap = new HashMap<>();
                List<SlRwork> groupProcessList = slRworkService.selectGroupProcessByRfworkId(rfwork.getRfworkId());
                for (SlRwork gp :groupProcessList) {
                    SlProcess slProcess = slProcessService.selectSlProcessByProcessId(gp.getProcessId());
                    if (StringUtils.isNotNull(slProcess)){
                        if(slProcess.getQuantify()!=null && slProcess.getQuantify().compareTo(BigDecimal.ZERO)>0 ){
                            if(gp.getRworkActual().compareTo(slProcess.getQuantify())<0){
                                //产量不够，记录工序ID和计算比例
                                BigDecimal bili = gp.getRworkActual().divide(slProcess.getQuantify(),2,RoundingMode.DOWN).setScale(2,RoundingMode.DOWN);
                                tmpMap.put(gp.getProcessId(),bili);
                            }
                        }
                    }
                }

                for (SlRwork rwork:slRworkList) {
                    //单项报工项总工资（工序工资*产量*重复次数）
                    BigDecimal estimatePay = rwork.getProcessPay().multiply(rwork.getRworkActual()).multiply(BigDecimal.valueOf(rwork.getRworkRepetitions())).setScale(2, RoundingMode.DOWN);
                    //看看在不在定量没达标的列表中,没达标按比例扣减
                    if(StringUtils.isNotEmpty(tmpMap)){
                        if (tmpMap.get(rwork.getProcessId())!=null){
                            estimatePay = estimatePay.multiply(tmpMap.get(rwork.getProcessId())).setScale(2,RoundingMode.DOWN);
                        }
                    }
                    //操作人列表
                    List<SlRworkRmember> memberList = slRworkRmemberService.selectSlRworkRmemberListByRworkId(rwork.getRworkId());
                    //操作人数
                    BigDecimal operatorNumber = BigDecimal.valueOf(memberList.size());
                    //非学徒员工
                    List<SlRworkRmember> nonApprenticeList = new ArrayList<>();

                    if (StringUtils.isNotEmpty(memberList)){
                        for (SlRworkRmember member: memberList) {
                            //学徒单独计算工资，并且调整平分的比例
                            if (ArrayUtil.contains(apprenticeIds, member.getLevelId())) {
                                //工作时长
                                BigDecimal mduration = member.getRmemberDuration();
                                //支付工资
                                BigDecimal memberPay = BigDecimal.ZERO;
                                //学徒系数
                                SlApprentice slApprentice = new SlApprentice();
                                slApprentice.setModuleId(rfwork.getModuleId());
                                slApprentice.setLevelId(member.getLevelId());
                                slApprentice = slApprenticeService.selectSlApprenticeByModuleAndLevel(slApprentice);
                                if(StringUtils.isNotNull(slApprentice)){
                                    //调整平分人数
                                    operatorNumber = operatorNumber.subtract(BigDecimal.valueOf(1)).add(slApprentice.getApprenticeDay());
                                    //小时工学徒
                                    if("Y".equals(member.getIsHourlyworker())){
                                        //默认小时工日薪
                                        BigDecimal defaultPay = slWsbase.getScBasepay();

                                        if(rwork.getModuleId().longValue()==3L){
                                            //水场模块下的找对应工序的日薪
                                            SlSa slSa = slSaService.selectSlSaByGprocessId(rwork.getGprocessId());
                                            if (StringUtils.isNotNull(slSa)){
                                                defaultPay = slSa.getSaPay();
                                            }
                                            //水场8-10算1天
                                            if(mduration.compareTo(BigDecimal.valueOf(8))>0 && mduration.compareTo(BigDecimal.valueOf(10))<0){
                                                memberPay = defaultPay;
                                            }else {
                                                memberPay = defaultPay.divide(workHours,2,RoundingMode.DOWN).multiply(mduration).setScale(2, RoundingMode.DOWN);
                                            }
                                        }else{
                                            //非水场按小时
                                            memberPay = defaultPay.divide(workHours,2,RoundingMode.DOWN).multiply(mduration).setScale(2, RoundingMode.DOWN);
                                        }
                                    }else{
                                        //正常学徒
                                        if(rwork.getModuleId().longValue()==3L){
                                            if(mduration.compareTo(BigDecimal.valueOf(8))>0 && mduration.compareTo(BigDecimal.valueOf(10))<0){
                                                memberPay = slApprentice.getApprenticePay().multiply(workHours).setScale(2, RoundingMode.DOWN);
                                            }else {
                                                memberPay = slApprentice.getApprenticePay().multiply(member.getRmemberDuration()).setScale(2, RoundingMode.DOWN);
                                            }
                                        }else {
                                            memberPay = slApprentice.getApprenticePay().multiply(member.getRmemberDuration()).setScale(2, RoundingMode.DOWN);
                                        }
                                    }
                                }
                                //更细操作人工资
                                member.setRmemberPay(memberPay);
                                slRworkRmemberService.updateSlRworkRmember(member);

                                //更新学徒员工报工单工资
                                SlWagesDay slWagesDay = slWagesDayService.selectSlWagesDayByRfworkIdAndUser(rwork.getRfworkId(),member.getRmemberUser());
                                if (StringUtils.isNotNull(slWagesDay)){
                                    slWagesDay.setProWages(slWagesDay.getProWages().add(memberPay));
                                    slWagesDayService.updateSlWagesDay(slWagesDay);
                                }
                            }else{
                                nonApprenticeList.add(member);
                            }

                        }

                        //非学徒员工的特殊系数人员的结算比例
                        if(StringUtils.isNotEmpty(nonApprenticeList)){
                            for (SlRworkRmember rmember:nonApprenticeList) {
                                SlSpecial slSpecial = slSpecialService.selectSlSpecialByUserName(rmember.getRmemberUser());
                                if (StringUtils.isNotNull(slSpecial)){
                                    if(rmember.getSsmId().longValue()==2L || rmember.getSsmId().longValue()==4L){
                                        //不参与生产
                                        if("1".equals(slSpecial.getIsProduce())){
                                            operatorNumber = operatorNumber.subtract(BigDecimal.valueOf(1));
                                        }else{
                                            if (slSpecial.getSsScale().compareTo(BigDecimal.valueOf(1))!=0){
                                                operatorNumber = operatorNumber.subtract(BigDecimal.valueOf(1)).add(slSpecial.getSsScale()).setScale(2,RoundingMode.DOWN);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        //非学徒员工计算薪资
                        BigDecimal averagePay;
                        //看看该工序工资平分不平分
                        SlProcess slProcess = slProcessService.selectSlProcessByProcessId(rwork.getProcessId());
                        if ("1".equals(slProcess.getIsBisect())){
                            averagePay= estimatePay;
                        }else {
                            averagePay= estimatePay.divide(operatorNumber, 2,RoundingMode.DOWN);
                        }

                        if(StringUtils.isNotEmpty(nonApprenticeList)){
                            for (SlRworkRmember rmember:nonApprenticeList) {
                                //员工出勤工资记录
                                SlWagesDay slWagesDay = slWagesDayService.selectSlWagesDayByRfworkIdAndUser(rwork.getRfworkId(),rmember.getRmemberUser());
                                //结算工资
                                BigDecimal tmpssmpay = averagePay;

                                Long ssmId = rmember.getSsmId();
                                if(ssmId==1){
                                    //固定工资
                                    rmember.setRmemberPay(averagePay);
                                }else if(ssmId==2){
                                    //机台长系数工资，看他和报工人是不是一人，是一人的话按系数算
                                    if(rmember.getRmemberUser().equals(rfwork.getRfworkUser())){
                                        SlSpecial slSpecial = slSpecialService.selectSlSpecialByUserName(rmember.getRmemberUser());
                                        if (StringUtils.isNotNull(slSpecial)){
                                            tmpssmpay = averagePay.multiply(slSpecial.getSsRatio());
                                        }
                                    }else {
                                        slWagesDay.setRfworkssmId(3L);
                                    }
                                    rmember.setRmemberPay(tmpssmpay);
                                    if (rwork.getModuleId().longValue()==3L||rwork.getModuleId().longValue()==2L){
                                        slWagesDay.setProWages(slWagesDay.getProWages().add(tmpssmpay));
                                    }
                                }else if(ssmId==3){
                                    //计件
                                    rmember.setRmemberPay(tmpssmpay);
                                    if (rwork.getModuleId().longValue()==3L||rwork.getModuleId().longValue()==2L){
                                        slWagesDay.setProWages(slWagesDay.getProWages().add(tmpssmpay));
                                    }
                                    //原皮库的存起来最后再算一遍平均的
                                    if(ypkUsers.contains(rmember.getRmemberUser())){
                                        slWagesDay.setIsYpk("0");
                                        //ypkDateList.add(rwork.getRworkDate());
                                    }
                                }else if(ssmId==4){
                                    //特殊系数，前面已记录，最后算
                                    //rmember.setRmemberPay(tmpssmpay);
                                }else if(ssmId==5){
                                    //小时工/日工

                                    //小时工默认薪资
                                    BigDecimal defaultPay = slWsbase.getScBasepay();
                                    SlSa slSa = slSaService.selectSlSaByGprocessId(rwork.getGprocessId());
                                    if (StringUtils.isNotNull(slSa)){
                                        defaultPay = slSa.getSaPay();
                                    }
                                    BigDecimal tmpMemberPay = BigDecimal.ZERO;
                                    tmpMemberPay = defaultPay.divide(workHours,2,RoundingMode.DOWN).multiply(rmember.getRmemberDuration()).setScale(2, RoundingMode.DOWN);

                                    if (rwork.getModuleId().longValue()==3L){
                                        if(rmember.getRmemberDuration().compareTo(BigDecimal.valueOf(8))>0 && rmember.getRmemberDuration().compareTo(BigDecimal.valueOf(10))<0){
                                            tmpMemberPay = defaultPay;
                                        }
                                    }
                                    rmember.setRmemberPay(tmpMemberPay);
                                    slWagesDay.setProWages(slWagesDay.getProWages().add(tmpMemberPay).setScale(2, RoundingMode.DOWN));

                                }
                                slRworkRmemberService.updateSlRworkRmember(rmember);
                                if (StringUtils.isNotNull(slWagesDay)){
                                    slWagesDayService.updateSlWagesDay(slWagesDay);
                                }

                            }
                        }
                    }
                }
            }
            //rfwork.setIsStatistics("0");    //标记已统计
            //slRfworkService.updateSlRfwork(rfwork);

        }
        //特殊系数开始
        if(StringUtils.isNotEmpty(lastAttendance)){
            Set<String> tmpUsers = new HashSet<>();

            for (SlAttendance attendance: lastAttendance) {
                //判断员工是否已经计算过了
                if (tmpUsers.isEmpty()){
                    tmpUsers.add(attendance.getUserName());
                }else {
                    if(tmpUsers.contains(attendance.getUserName())){
                        continue;
                    }
                }

                //特殊工作规则
                SlSpecial slSpecial = slSpecialService.selectSlSpecialByUserName(attendance.getUserName());
                if (StringUtils.isNotNull(slSpecial)){
                    //按什么平均1模块，2车间，3工序
                    String atype = slSpecial.getAverageType();
                    SlRwork queryRwork = new SlRwork();
                    queryRwork.setRworkDate(attendance.getRworkDate());
                    if("1".equals(atype)){
                        Long moduleId = slSpecial.getModuleId();
                        queryRwork.setModuleId(moduleId);
                    }else if("2".equals(atype)){
                        Long workshopId = slSpecial.getWorkshopId();
                        queryRwork.setWorkshopId(workshopId);
                    }else if("3".equals(atype)){
                        Long gprocessId = slSpecial.getGprocessId();
                        queryRwork.setGprocessId(gprocessId);
                    }
                    //所有包含对应平均的报工单
                    List<Long> rfworkIds = slRworkService.selectGroupRworkByAnyId(queryRwork);
                    int rfworkNum = rfworkIds.size();
                    BigDecimal averagePay = BigDecimal.ZERO;
                    if(StringUtils.isNotEmpty(rfworkIds)){
                        for (Long rfworkid:rfworkIds) {
                            BigDecimal rfworkPay = slRworkService.selectAllPayByRfworkId(rfworkid);
                            BigDecimal settlementDay = slAttendanceService.selectAllSettlementDaysByRfworkId(rfworkid);

                            averagePay =  rfworkPay.divide(settlementDay,2,RoundingMode.DOWN).add(averagePay).setScale(2,RoundingMode.DOWN);

                        }
                        //指定人的出勤天数
                        BigDecimal usreAttendanceDays = attendance.getAttendanceDay();
                        //报工单总平均工资/报工单数量X个人出勤天数X系数
                        BigDecimal perPay = BigDecimal.ZERO;
                        if (rfworkNum !=0){
                            perPay = averagePay.divide(BigDecimal.valueOf(rfworkNum),2, RoundingMode.DOWN).multiply(usreAttendanceDays).multiply(slSpecial.getSsRatio()).setScale(2, RoundingMode.DOWN);
                        }

                        SlWagesDay slWagesDay = slWagesDayService.selectSlWagesDayByRfworkIdAndUser(attendance.getRfworkId(),attendance.getUserName());
                        if (StringUtils.isNull(slWagesDay)){
                            SlWagesDay newSlWagesDay= new SlWagesDay();
                            newSlWagesDay.setLevelId(attendance.getLevelId());
                            newSlWagesDay.setSsmId(attendance.getSsmId());
                            newSlWagesDay.setProSettlement(attendance.getAttendanceDay().multiply(slSpecial.getSsScale()));
                            newSlWagesDay.setWagesSacoefficient(slSpecial.getSsRatio());
                            newSlWagesDay.setUserName(attendance.getUserName());
                            newSlWagesDay.setNickName(attendance.getNickName());
                            newSlWagesDay.setProDate(attendance.getRworkDate());
                            newSlWagesDay.setProDay(attendance.getAttendanceDay());
                            newSlWagesDay.setProWages(perPay);
                            newSlWagesDay.setWorkType("0");
                            slWagesDayService.insertSlWagesDay(newSlWagesDay);
                        }else {
                            slWagesDay.setProWages(perPay);
                            slWagesDayService.updateSlWagesDay(slWagesDay);
                        }

                    }

                }
                tmpUsers.add(attendance.getUserName());
            }
        }

        //原皮库平分开始
        SlWagesDay slWagesDay = new SlWagesDay();
        slWagesDay.setIsYpk("0");
        slWagesDay.setProDate(rworkDate);
        slWagesDay.setWorkType("0");
        List<SlWagesDay> ypklist =  slWagesDayService.selectSlWagesDayList(slWagesDay);
        if(StringUtils.isNotEmpty(ypklist)){
            //总出勤结算天数
            BigDecimal totalSettlement = BigDecimal.ZERO;
            //总金额
            BigDecimal totalWages = BigDecimal.ZERO;
            for (SlWagesDay wagesDay:ypklist) {
                totalSettlement = totalSettlement.add(wagesDay.getProSettlement());
                totalWages = totalWages.add(wagesDay.getProWages());
            }
            //基础金额
            BigDecimal baseWages = totalWages.divide(totalSettlement,2,RoundingMode.DOWN).setScale(2,RoundingMode.DOWN);
            for (SlWagesDay wagesDay:ypklist) {
                //重新赋值当天工资
                wagesDay.setProWages(baseWages.multiply(wagesDay.getProSettlement()).setScale(2,RoundingMode.DOWN));
                slWagesDayService.updateSlWagesDay(wagesDay);
            }
        }
        System.out.println("end------------车间日工资计算结束--------------");
    }

    @Transactional
    @Override
    public void countLingGongWsDay(SlRfwork paramRfwork)
    {
        System.out.println("start------------车间零工日工资计算开始--------------");

        //指定日期所有复核通过的计件报工单
        Date rworkDate = paramRfwork.getRfworkDate();

        //先删除当日所有零工工资记录
        slWagesDayService.deleteSlWagesDayByDate("1",rworkDate);

        //职级7初级8中级9高级学徒
        Long[] apprenticeIds = {new Long(7),new Long(8),new Long(9)};
        //1个出勤天=多少小时
        BigDecimal workHours = BigDecimal.valueOf(10);
        //原皮库所有成员
        List<String> ypkUsers = new ArrayList<>();
        List<SlTeamMember> teamMemberList = slTeamMemberService.selectSlTeamMemberListByTeamCode("ypk");
        if(StringUtils.isNotEmpty(teamMemberList)){
            for (SlTeamMember teamMember:teamMemberList) {
                ypkUsers.add(teamMember.getUserName());
            }
        }

        //零工开始
        List<SlRfwork> lgList = slRfworkService.selectAllApprovedSlRfworkListByDate("1",rworkDate);
        for (SlRfwork rfwork : lgList) {
            List<SlOddjobAttendance> slAttendanceList = slOddjobAttendanceService.selectAllSlOddjobAttendanceByRfworkId(rfwork.getRfworkId());
            if(StringUtils.isNotEmpty(slAttendanceList)){
                for (SlOddjobAttendance slAttendance :slAttendanceList) {
                    SlWagesDay slWagesDay = new SlWagesDay();
                    slWagesDay.setRfworkId(rfwork.getRfworkId());
                    slWagesDay.setModuleId(rfwork.getModuleId());
                    slWagesDay.setUserName(slAttendance.getUserName());
                    slWagesDay.setNickName(slAttendance.getNickName());
                    slWagesDay.setProDate(rfwork.getRfworkDate());
                    slWagesDay.setProDay(slAttendance.getAttendanceDay());
                    slWagesDay.setProWages(BigDecimal.ZERO);
                    slWagesDay.setWorkType("1");
                    slWagesDayService.insertSlWagesDay(slWagesDay);
                }
            }
            List<SlOddjob> oddJoblist = slOddjobService.selectSlOddjobListByRfworkId(rfwork.getRfworkId());
            if(StringUtils.isNotEmpty(oddJoblist)){
                for (SlOddjob slOddjob:oddJoblist) {
                    //工作时长
                    BigDecimal duration = slOddjob.getOddjobDuration();
                    //操作人列表
                    List<SlOddjobOmember> memberList =  slOddjobOmemberService.selectSlOddjobOmemberListByOddjobId(slOddjob.getOddjobId());
                    //计价
                    BigDecimal wmPay =  slOddjob.getWmPay();
                    //单位（1时、2天、3台）
                    String wmUnit = slOddjob.getWmUnit();
                    BigDecimal wages = BigDecimal.ZERO;
                    if("1".equals(wmUnit)){
                        //计价*时长
                        wages = wmPay.multiply(duration).setScale(2, RoundingMode.DOWN);
                    } else if ("2".equals(wmUnit)) {
                        // 计价/10*时长
                        wages = wmPay.divide(workHours,2, RoundingMode.DOWN).multiply(duration).setScale(2, RoundingMode.DOWN);
                    } else if ("3".equals(wmUnit)) {
                        // 计价/人数
                        wages = wmPay.divide(BigDecimal.valueOf(memberList.size()),2, RoundingMode.DOWN).setScale(2, RoundingMode.DOWN);
                    }
                    for (SlOddjobOmember member: memberList) {
                        SlWagesDay slWagesDay = slWagesDayService.selectSlWagesDayByRfworkIdAndUser(rfwork.getRfworkId(),member.getOmemberUser());
                        slWagesDay.setLevelId(member.getLevelId());
                        slWagesDay.setSsmId(member.getSsmId());

                        //学徒系数
                        if (ArrayUtil.contains(apprenticeIds, member.getLevelId())) {
                            SlApprentice slApprentice = new SlApprentice();
                            slApprentice.setModuleId(rfwork.getModuleId());
                            slApprentice.setLevelId(member.getLevelId());
                            slApprentice = slApprenticeService.selectSlApprenticeByModuleAndLevel(slApprentice);
                            BigDecimal tmpWages = wages;
                            if(StringUtils.isNotNull(slApprentice)){
                                tmpWages = slApprentice.getApprenticePay().multiply(duration).setScale(2, RoundingMode.DOWN);
                            }
                            slWagesDay.setProWages(slWagesDay.getProWages().add(tmpWages).setScale(2,RoundingMode.DOWN));

                        }else{
                            slWagesDay.setProWages(slWagesDay.getProWages().add(wages).setScale(2,RoundingMode.DOWN));
                        }


                        //原皮库的存起来最后再算一遍平均的
                        if(ypkUsers.contains(member.getOmemberUser())){
                            slWagesDay.setIsYpk("0");
                        }
                        slWagesDayService.updateSlWagesDay(slWagesDay);
                    }
                }
            }
            //rfwork.setIsStatistics("0");    //标记已统计
            //slRfworkService.updateSlRfwork(rfwork);

        }
        //原皮库零工开始
        SlWagesDay slWagesDay = new SlWagesDay();
        slWagesDay.setIsYpk("0");
        slWagesDay.setProDate(rworkDate);
        slWagesDay.setWorkType("1");
        List<SlWagesDay> ypklist =  slWagesDayService.selectSlWagesDayList(slWagesDay);

        if(StringUtils.isNotEmpty(ypklist)){
            //总出勤结算天数
            BigDecimal totalProday = BigDecimal.ZERO;
            //总金额
            BigDecimal totalWages = BigDecimal.ZERO;
            for (SlWagesDay wagesDay:ypklist) {
                totalProday = totalProday.add(wagesDay.getProDay());
                totalWages = totalWages.add(wagesDay.getProWages());
            }
            //基础金额
            BigDecimal baseWages = totalWages.divide(totalProday,2,RoundingMode.DOWN).setScale(2,RoundingMode.DOWN);
            for (SlWagesDay wagesDay:ypklist) {
                //重新赋值当天工资
                wagesDay.setProWages(baseWages.multiply(wagesDay.getProDay()).setScale(2,RoundingMode.DOWN));
                slWagesDayService.updateSlWagesDay(wagesDay);
            }
        }

        System.out.println("end------------车间零工日工资计算结束--------------");
    }
}
